var generator = require('../generator/generator');
var system = require('../model/system');

exports.selectSys = function(req,res,connection){
	system.selSys(connection,function(rows){
		if(rows != null && rows.length !=0) {
			res.send(rows);
		}else{
			res.send("none");
		}
	});

};


exports.addSys = function(req,res,connection){
	var sendData = req.body;
	var sysData = sendData.sysData;
	if(sysData.sysManagerId == null || sysData.sysManagerId == "") {
		sysData.sysManagerId = 0;
	}
	console.log("controller----addSys--sysData", sysData);
	system.addSys(connection, sysData, function(rows){
		if(rows != null && rows.length !=0 ){
			res.send("添加体系成功！");
		}else{
			res.send("添加体系失败！");
		}
	})
};

exports.updateSys = function(req,res,connection){
	var sendData = req.body;
	var sysData = sendData.sysData;
	var sysid = sendData.sysid;
	sysData.id = sysid;
	if(sysData.sysManagerId == null || sysData.sysManagerId == ""){
		sysData.sysManagerId = 0;
	}
	system.updateSys(connection,sysData,function(rows){
		if(rows != null && rows.length != 0) {
			res.send("更新体系成功！");
		}else{
			res.send("更新体系失败！");
		}
	});
};

exports.delSystem = function(req,res,connection){
	var sysid = req.query.sysid;
	system.deleteSys(connection, sysid, function(rows){
		res.send(rows);
	});
};

//校验体系名称是否重复
exports.checkSysName = function(req, res, connection) {
	// var sendData = req.params['sendData'] + '';
	var sendData = req.query.sendData;
	var dataJson = JSON.parse(sendData);
	var sysData = dataJson.sysData;
	var type = dataJson.type;
	var sendResult = "true";
	if(type == "post") {
		//新增模式
		system.selSysByName(connection, sysData.sysName, function(rows) {
			if(rows != null && rows.length !=0) {
				sendResult = "false";
			}
			res.send(sendResult);
		});
	}else{
		//更新模式
		var sysId = dataJson.sysid;
		system.selSysByName(connection, sysData.sysName, function(rows) {
			console.log("checkName--", rows);
			if(rows != null && rows.length != 0) {
				for(var i = 0; i < rows.length; i++) {
					if(rows[i].id != sysId) {
						sendResult = "false";
					}
				}
			}
			res.send(sendResult);
		});
	}
};
